package org.cem.backend;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginException;

import org.cem.security.CemSecurityPlugin;
import org.cem.security.RapLoginContext;
import org.cem.security.UserAdminSourceProvider;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.eclipse.ui.application.WorkbenchWindowAdvisor;
import org.eclipse.ui.services.ISourceProviderService;

/**
 * This workbench advisor creates the window advisor, and specifies
 * the perspective id for the initial window.
 */
public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {

	private static final String PERSPECTIVE_ID = "org.cem.perspectives.backend";

    public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
        return new ApplicationWorkbenchWindowAdvisor(configurer);
    }

	public String getInitialWindowPerspectiveId() {
		return PERSPECTIVE_ID;
	}

	@Override
	public void preStartup() {
		Subject subject = null;
		try {
			subject = CemSecurityPlugin.getLoginContext().getSubject();
		} catch (LoginException e) {
			e.printStackTrace();
		}
		getUserAdminSourceProvider().setSubject(subject);
	}

	@Override
	public boolean preShutdown() {
		getUserAdminSourceProvider().setSubject(null);
		return super.preShutdown();
	}
	
	private UserAdminSourceProvider getUserAdminSourceProvider() {
		IWorkbench workbench = PlatformUI.getWorkbench();
		ISourceProviderService sourceProviderService = (ISourceProviderService) workbench
				.getService(ISourceProviderService.class);
		return (UserAdminSourceProvider) sourceProviderService
				.getSourceProvider(UserAdminSourceProvider.ROLES);
	}
}
